//
//  RatingControl.swift
//  FoodTracker
//
//  Created by snow on 2018/4/11.
//  Copyright © 2018年 skcc. All rights reserved.
//

import UIKit

 class RatingControl: UIStackView {
    
    private var ratingButtons = [UIButton]()
    
    var rating = 0 {
        didSet {
            updateButtonSelectionStates()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButtons()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupButtons()
    }
    
    private func setupButtons(){
        
        //Clear any existing buttons
        
        for button in ratingButtons {
            
            removeArrangedSubview(button)
            
            button.removeFromSuperview()
            
        }
        
        ratingButtons.removeAll()
        
        //Load Button Images
        
        let bundle = Bundle(for: type(of: self))
        
        let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
        
        let emptyStar = UIImage(named: "emptyStar", in: bundle, compatibleWith: self.traitCollection)
        
        let highlightedStar = UIImage(named: "highlightedStar", in: bundle, compatibleWith: self.traitCollection)

        
        for index in 0..<starCount {
            
            
            //Create the button
            let button = UIButton()
            
            
            button.setImage(emptyStar, for: .normal)
            
            button.setImage(filledStar, for: .selected)
            
            button.setImage(highlightedStar, for: .highlighted)
            
            button.setImage(highlightedStar, for: [.highlighted,.selected])
            
            
            //Add constraints
            button.translatesAutoresizingMaskIntoConstraints = false
            
            button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true
            
            button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true
            
            
            // Set the accessibility label
            
            button.accessibilityLabel = "Set \(index + 1) star rating"
            
            //Setup the button action
            button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)
            
            
            //Add the button to the stack
            addArrangedSubview(button)
            
            
            // Add the new button to the rating button array
            
            ratingButtons.append(button)
        }
        
        
        updateButtonSelectionStates()
        
    }
    
    @objc func ratingButtonTapped(button: UIButton){
        guard let index = ratingButtons.index(of: button) else {
            fatalError("The Button,\(button),is not in the ratingBUttons array:\(ratingButtons)")
        }
        
        let selectedRating = index + 1
        
        
        if selectedRating == rating {
            rating = 0
        } else {
            rating = selectedRating
        }
    }
    
    @IBInspectable var starSize:CGSize = CGSize(width: 44.0, height: 44.0){
        didSet {
            setupButtons()
        }
    }
    
    @IBInspectable var starCount = 5 {
        didSet {
            setupButtons()
        }
    }
    
    private func updateButtonSelectionStates(){
        
        for (index,button) in ratingButtons.enumerated() {
            
            button.isSelected = index < rating
            
            // Set the hint string for the currently selected star
            
            let hintString: String?
            
            if rating == index + 1 {
                
                hintString = "Tao to reset the rating to zero."
                
            } else {
                
                hintString = nil
                
            }
            
            // Cakcylate the value string
            
            let valueString : String
            
            switch (rating) {
                
            case 0:
                
                valueString = "No rating set."
                
            case 1:
                
                valueString = "1 star set."
                
            default :
                
                valueString = "\(rating) stars set."
                
            }
            
            
            
            // Assign the hint string and value string
            
            button.accessibilityHint = hintString
            
            button.accessibilityHint = valueString
        }
        
        
    }
    
}
